<template>
  <!-- onemap -->
  <div :class="['checkmaps ',start_draw_status==true?'draw':'']"
    style="display: flex;height: 100%;min-width: 1446px;position: relative;overflow: hidden;">
    <div class="mapDivs" id="mapDivs">
      <div id="mapDiv1" @mouseenter="mouseenter('mapDiv1')">
        <div class="standard-map__mouse-position"
          style="color: #0c0c0c;background-color: white;font-size: 16px;right: 10px;left: auto;">
          <a-space>
            <span>
              已选择:
            </span>
            <span v-show="select_featrue.properties">
              {{select_featrue.properties?select_featrue.properties.JVBH:''}}
            </span>
            <span v-show="select_featrue.properties">
              状态:
            </span>
            <span v-show="select_featrue.properties">
              {{select_featrue.properties?GetOneIdStatusText(select_featrue.properties.status):''}}
            </span>
            <span v-show="select_featrue.properties">
              修改状态:
            </span>
            <span v-show="select_featrue.properties">
              <a-select style="width: 150px" @change="select_featrue_status_change" v-model="select_featrue_status">
                <a-select-option :value="item.status" v-for="(item,index) in all_status" :key="index"
                  v-show="item.status>=0">{{item.name}}</a-select-option>
              </a-select>
            </span>
          </a-space>
        </div>
        <div class="message-bar" >
          <a-space ref="tools" size="small">
            <span class="tiam-span">2002</span>
            <span class="tiam-span" style="margin-left: 100px;">2009</span>
          </a-space>
        </div>
      </div>
      <!-- <div id="mapDiv2"  @mouseenter="mouseenter('mapDiv2')">
          
        </div> -->
      <ul class="map-tools standard-map__map-tool">
        <a-tooltip placement="bottom">
          <template slot="title">
            <span>{{draw_status?"停止勾绘":"开始勾绘"}}</span>
          </template>
          <span class="map-tools__item" @click="start_draw">
            <svg aria-hidden="true" class="svg-icon">
              <use xlink:href="#icon-map-tool-draw-polygon"></use>
            </svg>
          </span>
        </a-tooltip>
        <a-tooltip placement="bottom">
          <template slot="title">
            <span>删除已绘图形</span>
          </template>
          <span class="map-tools__item" @click="clear_draw">
            <svg aria-hidden="true" class="svg-icon">
              <use xlink:href="#icon-map-tool-clear"></use>
            </svg>
          </span>
        </a-tooltip>
      </ul>
      <div id="line">
        <div class="line-ico">
          <a-icon type="swap" /> 
        </div>
      </div>
    </div>
    <div id="task4" style="border: 2px solid gray;">
        <a-row style="margin: 5px;">
          <a-space>
            <span>状态:
              <a-select style="width: 150px" @change="status_change" v-model="detail_status">
                <a-select-option :value="item.status" v-for="(item,index) in all_status" :key="index">{{item.name}}
                </a-select-option>
              </a-select>
            </span>
            <a-tooltip placement="bottom" style="margin-left: 5px;">
              <template slot="title"><span>重置所有的要素状态为未确定</span></template>
              <a-button @click="reset_to" type="primary">重置</a-button>
            </a-tooltip>
            
             <!-- <a-checkbox @change="onChange_refresh" style="margin-left: 40px;" autoFocus="false" ref="Change_auto" :checked="auto_refresh">动态刷新</a-checkbox>
                  <a-tooltip placement="bottom" style="margin-left: 5px;">
                    <template slot="title"><span>勾选此项将自动只显示显示范围内的要素</span></template>
                    <a-icon type="question-circle" />
                  </a-tooltip> -->
          </a-space>
        </a-row>
        <a-row style="margin: 5px;">
          <a-table :columns="columns" :data-source="task_ai_details" bordered :pagination="check_pagination"
            size="small" :customRow="RowEvents" @change="changeEvent">
            <span slot="JVBH" slot-scope="text, record">
              <span class="menu-name" style="user-select: text;">{{record.properties.JVBH}}</span>
            </span>
            <span slot="status" slot-scope="text, record">
              <a-badge :color="GetOneIdStatusColor(record.properties.status)"
                :text="GetOneIdStatusText(record.properties.status)" />
            </span>
          </a-table>
        </a-row>
    </div>
    <draw_end_check></draw_end_check>
    <a-drawer
      title="操作帮助"
      placement="left"
      :closable="false"
      :visible="help_visible"
      @close="helpClose"
      width="40%"
    >
      <div class="props">
          <ul>
            <li>
              <span class="values__label">1</span>
              <span class="values text">如果没有你的任务则为空</span>
            </li>
            <li>
              <span class="values__label">2</span>
              <span class="values text" style="-webkit-box-orient: unset;">在图斑选择状态下,状态快捷键：结果错误(0)、结果正确(1)、季节性变化(2)、云雪差异(3)、影像错位(4)、结果新增(5)、删除(delete、d)。</span>
            </li>
            <li>
              <span class="values__label">3</span>
              <span class="values text">地图放大缩小:放大(上箭头)、缩小(下箭头)</span>
            </li>
            <li>
              <span class="values__label">4</span>
              <span class="values text">图斑编辑:编辑开关(e)、编辑取消(esc).</span>
            </li>
          </ul>
        </div>
    </a-drawer>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        active_task: {},
        tocog: {},
        ol_map: null,
        zoom: 19,
        maxZoom: 22,
        minZoom: 12,
        all_status: [
          {
            name: "全部",
            status: -2,
          },
          {
            name: "未确定",
            status: -1,
          },
          {
            name: "结果错误",
            status: 0,
          },
          {
            name: "结果正确",
            status: 1,
          },
          {
            name: "季节性变化",
            status: 2,
          },
          {
            name: "云雪差异",
            status: 3,
          },
          {
            name: "影像错位",
            status: 4,
          },
          {
            name: "结果新增",
            status: 5,
          },
        ],
        detail_status: -2,
        task_ai_details_old: [],
        BH_max: 0,
        task_ai_details: [],
        columns: [{
            title: 'ID',
            scopedSlots: {
              customRender: 'JVBH'
            },
            dataIndex: 'name',
            width: 130,
            align: 'center'
          },
          {
            title: '状态',
            scopedSlots: {
              customRender: 'status'
            },
            width: 80,
            align: 'center'
          },
        ],
        check_pagination: {
          size: 'small',
          pageSize: 10,
          // simple: true,
          showTotal: (total, range) => {
            return `共 ${total},${range[0]}/${range[1]}`
          },
        },
        RowEvents: record => ({
          on: {
            dblclick: () => {
              this.dblclick(record);
            },
          }
        }),
        activeFeatrueProps: {},
        show_tool: false,
        draw_status: false,
        auto_refresh: false,
        select_featrue: {},
        select_featrue_status: 0,
        upload: false,
        upload_status: {
          num: 0,
          count: 0,
          percent: 0,
        },



        help_visible:false






      }
    },
    components: {
      draw_end_check: () => import('./draw_end_check.vue'),
    },
    mounted() {
      this.InitMap()
      setTimeout(() => {
        this.get_show_task_details();
      }, 500);
      this.$mitt.$on('draw_end_check_back', (valus) => {
        if (valus.status == true) {
          this.update_value(valus)
        }
      });
      this.$mitt.$on('onmoveend_back', (valus) => {
        this.update_task_ai_details(valus)
      });
      this.init_keydown();

    },
    methods: {
      init_keydown() { //当前页面监视键盘输入
        document.onkeydown = (e) => {
          let e1 = e || event || window.event || arguments.callee.caller.arguments[0] //事件对象兼容
          let set_key = true
          if (e1) {
            let keyCode = e1.keyCode
            if (keyCode == 38) { //上箭头
              this.setZoom(1)
            } else if (keyCode == 40) { //下箭头
              this.setZoom(-1)
            } else if (keyCode == 27) { //esc
              this.abortDrawing()
            }else if (keyCode == 46||keyCode == 68) { //delete
              this.delete_select()
            }else if (keyCode == 69) { //e
              this.start_draw()
            }else if (keyCode >=48 && keyCode <54) {//1 2
              this.select_featrue_status=keyCode-48
              this.select_featrue_status_change_fn()
            }
            else if (keyCode ==112) {//F1
              this.help_visible==true?this.helpClose():this.HelpOpen()
            }
            else {
              set_key = false
            }
          }
          if (set_key) {
            e.stopPropagation();
            e.preventDefault();
          }
        }
      },
      HelpOpen(){
        this.help_visible=true
      },
      helpClose(){
        this.help_visible=false
      },
      GetTiFName(num){
        if(num==1){
          return this.get_tif_time(this.get_tif_name(this.tocog,"preimage"))
        }
        else if(num==2){
          return this.get_tif_time(this.get_tif_name(this.tocog,"lstimage"))
        }
      },
      onChange_refresh() {
        this.auto_refresh = !this.auto_refresh
        if (this.auto_refresh) {
          this.ol_map.set("moveend_refresh", this.auto_refresh, this.update_task_ai_details)
        } else {
          this.ol_map.set("moveend_refresh", this.auto_refresh)
        }
        this.common_update_task_ai_details();
      },
      GetOneIdStatusColor(_status) {
        let status_Color = "";
        if (_status < 0) {
          status_Color = "gray"
        }
        else{
          status_Color = "green"
        }
        // if (_status == 0) {
        //   status_Color = "gray"
        // } else if (_status == 1) {
        //   status_Color = "green"
        // } else if (_status == 2) {
        //   status_Color = "red"
        // } else if (_status == 3) {
        //   status_Color = "green"
        // } else {
        //   status_Color = "gray"
        // }
        return status_Color
      },
      GetOneIdStatusText(_status) {
        let index = this.all_status.findIndex((val) => {
          return val.status == _status - 0
        })
        if (index >= 0) {
          return this.all_status[index].name
        }
        return "";
      },
      get_tif_name(tocog, imgprop = "lstimage") {
        let _tif_name = "";
        if (tocog) {
          _tif_name = tocog[imgprop]
        }
        if (_tif_name) {
          let names = _tif_name.split("/")
          _tif_name = names[names.length - 1].replace(".tif", "").trim()
        }
        return _tif_name
      },
      status_change() {
        this.common_update_task_ai_details();
      },

      select_featrue_status_change() {
        this.select_featrue_status_change_fn();
      },
      select_featrue_status_change_fn(){
        let index0 = this.get_fc_index_from_details_old_by_prop(["JVBH"], [this.select_featrue.properties.JVBH])
        if (index0 >= 0) {
          this.task_ai_details_old[index0].properties.status = this.select_featrue_status
          this.task_ai_details_old[index0].properties.time = (new Date()).getTime()
          this.select_featrue = this.task_ai_details_old[index0]
          //刷新
          this.common_update_task_ai_details();
        }
      },
      delete_select(){
        let select_featrue_jvbh=this.select_featrue?.properties?.JVBH
        if(select_featrue_jvbh){
          let find_index = this.get_fc_index_from_details_old_by_prop(["JVBH"], [select_featrue_jvbh])
          if (find_index >= 0) {
            this.task_ai_details_old.splice(find_index, 1)
          }
          this.select_featrue={};
          this.common_update_task_ai_details();
        }
        this.common_update_task_ai_details();
      },
      reset_to(){
        this.task_ai_details_old.forEach((val) => {
          if(val.properties.status==0){
            if(val.properties.time>0){

            }
            else{
              val.properties.status=-1
            }
          }
        })
        this.common_update_task_ai_details();
      },
      get_check_task() {
        this.active_task = {}
        this.tocog = {}
        if (this.ol_map) {
          this.ol_map.clearMap(1)
          this.ol_map.clearMap(2)
        }
        let qs = {
          status: 0,
        }
        this.$common_apis.axios_get('/search_checkai_task?', qs, true)
          .then(result => {
            if (result) {
              this.active_task = result
              this.tocog = result.jdcheck.tocog
              this.InitMap()
              setTimeout(() => {
                this.get_check_task_details()
              }, 300);
            } else {
              this.$message.info("没有AI检测精度任务")
            }
          });
      },
      get_check_task_details(pagenum = 1) {
        this.task_ai_details_old = []
        let qs = {
          mergeid: this.active_task.mergeid,
          pagesize: 10,
          pagenum: pagenum,
        }
        if (this.detail_status >= 0) {
          qs.status = this.detail_status
        }
        this.$common_apis.axios_get('/search_checkai_task_details?', qs, true)
          .then(result => {
            if (result) {
              if (result.length > 0) {
                result.forEach((val, index) => {
                  val.key = index
                  //ZT150825000005
                  let bh = val.properties.JVBH.substr(8, 6)
                  let bh_int = bh - 0
                  if (bh_int > this.BH_max) {
                    this.BH_max = bh_int
                  }
                })
                this.task_ai_details_old = result
                this.get_show_task_details();
              }
            }
          });
      },
      get_show_task_details() {
        if (this.detail_status == -2) {
          this.task_ai_details = this.task_ai_details_old
        } else {
          this.task_ai_details = this.task_ai_details_old.filter((val) => {
            return val.properties.status == this.detail_status
          })
        }
        this.ol_map.addFeatrue(this.task_ai_details, true);
      },
      update_task_ai_details(jsvhs) {
        this.task_ai_details = []
        for (let index = 0; index < jsvhs.length; index++) {
          let element = jsvhs[index];
          let index0 = -1
          if (this.detail_status < 0) {
            index0 = this.get_fc_index_from_details_old_by_prop(["JVBH"], [element])
          } else {
            index0 = this.get_fc_index_from_details_old_by_prop(["JVBH", "status"], [element, this.detail_status])
          }
          if (index0 >= 0) {
            this.task_ai_details.push(this.task_ai_details_old[index0])
          }
        }
        this.ol_map.addFeatrue(this.task_ai_details, true);
      },
      common_update_task_ai_details() {
        if (this.auto_refresh) {
          this.ol_map.force_moveend();
        } else {
          this.get_show_task_details()
        }
      },
      get_fc_index_from_details_old_by_prop(names, values) {
        return this.task_ai_details_old.findIndex((val) => {
          let status = true;
          for (let index = 0; index < names.length; index++) {
            let element = names[index];
            if (val.properties[element] != values[index]) {
              status = false
            }
          }
          return status
        })
      },
      get_fc_from_details_old_by_prop(names, values, equal = true) {
        return this.task_ai_details_old.filter((val) => {
          let status = true;
          for (let index = 0; index < names.length; index++) {
            let element = names[index];
            if (equal) {
              if (val.properties[element] != values[index]) {
                status = false
              }
            } else {
              if (val.properties[element] == values[index]) {
                status = false
              }
            }
          }
          return status
        })
      },
      //-1未确定 0结果错误 1结果正确 2季节性变化  3云雪差异 4影像错位
      get_next_jvbh() {
        this.BH_max = this.BH_max + 1
        let next = `ZT150802`
        let index_string = this.BH_max + "";
        if (index_string.length < 6) {
          let _length = index_string.length
          for (let j = 0; j < 6 - _length; j++) {
            index_string = "0" + index_string;
          }
        }
        next = `ZT150802${index_string}`
        return next;
      },
      update_value(valus) {
        let fc = valus.fc
        let fcolds = valus.fcolds
        //获取最新的编号
        let JVBH = this.get_next_jvbh();
        let JCMJ = this.ol_map.get_Featrue_area(fc)
        let coordinates = this.ol_map.get_Featrue_Coordinates(fc)
        if (fcolds.length == 0) {
          //新增
          this.task_ai_details_old.push({
            properties: {
              time: (new Date()).getTime(),
              JCMJ: JCMJ,
              JVBH: JVBH,
            },
            geometry: {
              type: {
                type: String,
                default: "Polygon"
              },
              coordinates: coordinates,
            },
            key: this.BH_max
          })
        } else {
          if (fcolds.length == 1) {
            let find_index = this.get_fc_index_from_details_old_by_prop(["JVBH"], [fcolds[0]])
            if (find_index >= 0) {
              this.task_ai_details_old[find_index].geometry.coordinates = coordinates
              this.task_ai_details_old[find_index].properties.JCMJ = JCMJ
            }
          } else {
            //删除旧的要素
            let lgth = fcolds.length
            while (lgth > 0) {
              let find_index = this.get_fc_index_from_details_old_by_prop(["JVBH"], [fcolds[0]])
              if (find_index >= 0) {
                this.task_ai_details_old.splice(find_index, 1)
              }
              fcolds.splice(0, 1)
              lgth = fcolds.length
            }
            //添加新的要素
            this.task_ai_details_old.push({
              properties: {
                time: (new Date()).getTime(),
                JCMJ: JCMJ,
                JVBH: JVBH,
              },
              geometry: {
                type: {
                  type: String,
                  default: "Polygon"
                },
                coordinates: coordinates,
              },
              key: this.BH_max
            })
          }
        }
        this.common_update_task_ai_details();
        this.clear_draw()
      },
      dblclick(record) {
        this.ol_map.zoom_to_feature({
          JVBH: record.properties.JVBH
        })
      },
      mouseenter(_div) {
        document.getElementById(_div).focus()
      },
      InitMap() {
        let center = [114.037,39.047]
        let layers1 = [
          
          new ol.layer.Image({
              source:new ol.source.ImageStatic({
                url: "https://nmgwxyy.cn/alatan/static/js_public/test_show/hanyang2009.jpg",
                imageExtent: [112.936489,38.075115,115.072489,40.047915],
                imageSize:[6000, 7200]
            })
          }),
          new ol.layer.Image({
              source:new ol.source.ImageStatic({
                url: "https://nmgwxyy.cn/alatan/static/js_public/test_show/hanyang2002.jpg",
                imageExtent: [112.936489,38.075115,115.072489,40.047915],
                imageSize:[6000, 7200]
            })
          }),
        ]
        if (!this.ol_map) {
          this.ol_map = new this.ol_mapClass({
            center: center,
            target1: 'mapDiv1',
            zoom: 15,
            layers1: layers1,
            swip_layer_index: 1
          })
          this.ol_map.upDate()
          this.ol_map.set("click_featrue", true, (_select) => {
            if (_select.properties) {
              let index0 = this.get_fc_index_from_details_old_by_prop(["JVBH"], [_select.properties.JVBH])
              if (index0 >= 0) {
                this.select_featrue = this.task_ai_details_old[index0]
                this.select_featrue_status = this.select_featrue.properties.status
              }
            } else {
              this.select_featrue = {}
            }
          })
        } else {
          this.ol_map.update_layer(layers1, 1)
          this.ol_map.update_center(center)
        }
        setTimeout(() => {
          this.initSwipeDom((xy) => {
            this.ol_map.SwipeLayer(xy)
          })
        }, 500);

      },
      start_draw() {
        this.draw_status = this.ol_map.initDraw(this.DrawEnd);
      },
      DrawEnd(fc, fcolds) {
        this.$mitt.emit("draw_end_check", {
          fc: fc,
          fcolds: fcolds
        })
      },
      clear_draw() {
        this.ol_map.clearDrawLayer()
      },
      abortDrawing() {
        if (this.draw_status) {
          this.ol_map.abortDrawing()
        }
      },
      setZoom(zoom) {
        this.ol_map.setZoom(zoom)
      },
      
      upload_to_server() {
        let that = this;
        let hasDone = this.task_ai_details_old.length - this.get_fc_from_details_old_by_prop(["status"], [-1]).length
        let count = this.task_ai_details_old.length
        if (hasDone != count) {
          this.$confirm({
            title: `还有${count-hasDone}个图斑未确认,是否继续上传同步?`,
            onOk() {
              that.upload_to_server_async();
            },
            onCancel() {},
            class: 'test',
          });
        } else {
          that.upload_to_server_async();
        }
      },
      async upload_to_server_async() {
        this.upload=true;
        let will_be_up = this.get_fc_from_details_old_by_prop(["status"], [-1], false)
        // return
        this.upload_status.count = will_be_up.length
        for (let index = 0; index < will_be_up.length; index++) {
          let element = will_be_up[index];
          let qs = {
            mergeid: this.active_task.mergeid,
            props: JSON.stringify(element)
          }
          let result = await this.$common_apis.axios_post('/update_checkai_task_details?', qs, true)
          if (result) {
            this.upload_status.num = index + 1
            this.upload_status.percent = parseInt((index + 1) / will_be_up.length * 100)
          }
        }
        this.$message.info("上传成功,清空任务")
        this.task_ai_details_old=[]
        this.common_update_task_ai_details();
        this.upload=false;
      },
      initSwipeDom(cb) {
        let line = document.getElementById("line");
        var obj = {};
        let max_width = document.getElementById("mapDiv1").offsetWidth
        line.onmousedown = null
        line.onmousedown = function (event) {
          var e = event || window.event;
          // 鼠标点击元素那一刻相对于元素左侧边框的距离=点击时的位置相对于浏览器最左边的距离-物体左边框相对于浏览器最左边的距离
          obj.diffX = e.clientX - this.offsetLeft;
          document.onmousemove = function (event) {
            var e = event || window.event;
            var moveX = e.clientX - obj.diffX;
            if (moveX < 0) {
              moveX = 0
            } else if (moveX > max_width - line.offsetWidth) {
              moveX = max_width - line.offsetWidth
            }
            line.style.left = moveX + 'px';
            // moveX=moveX+4
            cb([moveX+4, 0])
            //重新渲染图层
            //map.render();
          };
          document.onmouseup = function () {
            this.onmousemove = null;
            this.onmouseup = null;
          }
        };
        //获取第一次出现的位置
        let firstX = line.offsetLeft + line.offsetWidth
        cb([firstX, 0])
      },
    },
    beforeDestroy() {
      document.onkeydown = undefined
      this.$mitt.$off('draw_end_check_back');
      this.$mitt.$off('onmoveend_back');
    },
  }
</script>

<style>
  .checkmaps .mapDivs {
    width: calc(100% - 370px);
    height: 100%;
    position: relative;
    display: flex;
  }

  #task4 {
    width: 370px;
    height: 100%
  }

  .mapDivs #mapDiv1,
  .mapDivs #mapDiv2 {
    width: calc(100% - 0px);
  }

  .standard-map__map-tool {
    position: absolute;
    top: 8px;
    right: 8px;
    z-index: 10;
  }

  .map-tools__item {
    display: inline-block;
    cursor: pointer;
    width: 30px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    -webkit-box-shadow: rgb(0 0 0 / 25%) 0 0 4px 0;
    box-shadow: 0 0 4px 0 rgb(0 0 0 / 25%);
    margin: 0 2px;
    padding: 1px;
    background: hsla(0, 0%, 100%, .92);
    border-radius: 4px;
  }

  .map-tools__item svg {
    height: 28px;
    width: 28px;
  }

  .draw #mapDiv1 {
    /* zoom: 0.5; */
    width: 401px;
    height: 401px;
    position: absolute;
    z-index: 1;
  }

  .draw #mapDiv2 {
    width: 100%;
  }

  .standard-map__mouse-position {
    position: absolute;
    bottom: 8px;
    left: 10px;
    font-size: 12px;
    z-index: 3;
    color: #000000;
    background-color: white;
  }

  #line {
    width: 4px;
    height: 100%;
    position: absolute;
    top: 0;
    left: calc(50% - 5px);
    background-color: #1890ff;
    border: 1px solid #1890ff;
    z-index: 2;
    cursor: pointer;
  }
  .line-ico {
    position: absolute;
    top: 50%;;
    left: -10px;
    width: 24px;
    height: 24px;
    line-height: 24px;
    text-align: center;
    border-radius: 100%;
    color: #fff;
    border: 1px solid #5883f4;
    background-color: #5883f4;
}
</style>